package com.example.chupachups;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.AnimationDrawable;
import android.util.Log;
import android.view.Menu;
import android.view.WindowManager;
import android.widget.ImageView;

public class MainActivity extends Activity {
	
	
	private static final String TAG = "MainActivity";
	public static String SERVER_RESPONSE = "null";
	private ImageView img;
	private AnimationDrawable frameAnimation;
	private Intent intent;
	private String vidUrl;
	private Handler handler;
	private Runnable r;
	protected Object postTask = null;
	private String videoRequestUrl;
	public static final String PREFS_NAME = "ChupaPrefsFile";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    	Log.v(TAG, "ON CREATE");
		MainActivity.SERVER_RESPONSE = "null";
    	handler = null;
    	r = null;
    	
		intent = getIntent();
		videoRequestUrl = intent.getStringExtra("videoRequestUrl");
		if(videoRequestUrl==null){
			videoRequestUrl = "http://chupa-test.appspot.com/retrievevid1";
		}

        img = (ImageView)findViewById(R.id.simple_anim);
        img.setBackgroundResource(R.drawable.simple_animation);

        frameAnimation = (AnimationDrawable) img.getBackground();

        frameAnimation.start();
        
        callAsynchronousTask();

    }
    
    protected void onPause() {
    	super.onPause();
    }
    
    protected void onStop() {

    	Log.v(TAG, "ON STOP");
		super.onStop();
    	frameAnimation.stop();
    }

    protected void onRestart() {

		super.onRestart();
		MainActivity.SERVER_RESPONSE = "null";
    	Log.v(TAG, "ON RESTART");
    	handler = null;
    	r = null;
    	img.setBackgroundResource(R.drawable.simple_animation);
    	frameAnimation.start();
    	callAsynchronousTask();
    }
    
    
    public void callAsynchronousTask() {
    	
    	if(handler == null){
    		handler = new Handler(); 
    		r = new Runnable()
	        {
	            public void run() 
	            {
	                if(SERVER_RESPONSE.contains("no")||SERVER_RESPONSE.contains("null")){
	                	postTask = new PostTask().execute(videoRequestUrl);
	                    handler.postDelayed(r, 1000);
	                }else{
	                	loadYouTubeVideo();
	                }
	            }
	        };
    	}
    	handler.postDelayed(r, 1000);
    	
    	/*Log.v(TAG, "callAsynchronousTask");
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {       
            @Override
            public void run() {
                handler.post(new Runnable() {

					public void run() {       
                        try {
                        	Log.v(TAG, "SERVER_RESPONSE: "+SERVER_RESPONSE);
                        	Log.v(TAG, "getActiveVid: "+getActiveVid());
                        	if(SERVER_RESPONSE.contains("no")||SERVER_RESPONSE.contains("null")){
                        		if(getActiveVid()==1){
                                	new PostTask().execute(MainActivity.vid1url);
                        		}else{
                                	new PostTask().execute(MainActivity.vid2url);
                        		}
                        	}else{
                        		cancel();
                        		loadYouTubeVideo();
                        	}
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                        }
                    }

                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 1000); */
    }
    

	private void loadYouTubeVideo() {
		
		frameAnimation.stop();
		img.setBackgroundResource(R.drawable.happy_animation);
        frameAnimation.start();
        JSONArray jArray;
		try {
			jArray = new JSONArray(SERVER_RESPONSE);
			JSONObject jObject = jArray.getJSONObject(0);
			final String videoid = jObject.getString("id");
			final String message = jObject.getString("message");
			final Handler launchHandler = new Handler();
    		final Runnable launchRunnable = new Runnable()
    		{
	            public void run() 
	            {
	            	frameAnimation.stop();
	            	Log.v(TAG,"GOT VIDEO: "+videoid+" AND MESSAGE: "+message);
                	Intent myIntent = new Intent(MainActivity.this, YouTubeActivity.class);
            		myIntent.putExtra("videoid", videoid);
            		myIntent.putExtra("message", message);
            		myIntent.putExtra("videoRequestUrl", videoRequestUrl);
            		MainActivity.this.startActivity(myIntent);
	            }
	        };
			
		    launchHandler.postDelayed(launchRunnable, 3000);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
    
    
    
    
 // The definition of our task class
    private class PostTask extends AsyncTask<String, Integer, String> {

	@Override
    protected void onPreExecute() {
       super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
       String url=params[0];
       if(SERVER_RESPONSE.contains("no")||SERVER_RESPONSE.contains("null")){
    	   URLConnection feedUrl = null;
	   		try {
	   			feedUrl  = new URL(url).openConnection();
	   		} catch (MalformedURLException e) {
	   		   	Log.v("ERROR","MALFORMED URL EXCEPTION");
	   		} catch (IOException e) {
	   		    e.printStackTrace();
	   		}
	   		try {
	   			InputStream in = feedUrl.getInputStream();
	   			
	   			String json = convertStreamToString(in);
	           	Log.v(TAG, "json retrieved: "+json);
	   			MainActivity.SERVER_RESPONSE = json;
	   			
	   		}catch(Exception e){
	              Log.v(TAG, "E ...");
	              e.printStackTrace();
	   		}
       }else{
    	   cancel(true);
       }

       return "All Done!";
		
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
       super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
       super.onPostExecute(result);
    }
    }

    private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
    	  BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
    	  StringBuilder sb = new StringBuilder();
    	  String line = null;
    	  try {
    	    while ((line = reader.readLine()) != null) {
    	      sb.append(line + "\n");
    	    }
    	  } catch (IOException e) {
    	    e.printStackTrace();
    	  } finally {
    	    try {
    	      is.close();
    	  } catch (IOException e) {
    	    e.printStackTrace();
    	  }
    	}
    	return sb.toString();
    	 }

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


   
}
